/**
 * 套餐插件
 * author: 梦幻开发组(damao)
 * QQ: 523994553
 * date: 2013-08-24
 * website: http://www.dreamfans.net
 */
(function($){

	//main
	$.fn.package = function(options){
		//new实例化对象
		new _package(this,options);
		return this;
	}

	//构造
	function _package(obj,options){
		this.obj = obj;
		this.settings = $.extend({}, this.defaults, options);
		this.init();
	}

	//默认值
	_package.prototype.defaults = {
		name : null,//套餐字段名称
		objA : null,//对象A
		objB : null,//对象B
		data : null,//套餐表单数据值
		preName : null,
		imgPre : null,//图片路径前缀
		objBdrag : false,//对象B是否可拖动排序
		callback : null//回调函数
	}

	//init
	_package.prototype.init = function(){
		var obj = $(this.obj);
		var settings = this.settings;
		var that = this;
		//初始化套餐的详细参数
		that.update_table_html();
		that.initCache();
		that.getCache();
		//相关的事件绑定促发事件
		that.eventBind();
	}

	//相关的事件绑定促发事件
	_package.prototype.eventBind = function(){
		var obj = $(this.obj);
		var that = this;
		var settings = this.settings;

		//objA 促发事件
		if(settings.objA){
			//objA添加一行
			$(settings.objA).parents('table.change_table').find('tr.thead').on('mouseup','.add_tr',function(){
				that.setCache();
				that.update_table_html();
				that.getCache();
			});
			//objA删除一行
			$(settings.objA).parents('table').on('reduse',function(){
				that.setCache();
				that.update_table_html();
				that.getCache();
			});
			//objA onchange时
			$(document).on('change',settings.objA,function(){
				that.setCache();
				that.update_table_html();
				that.getCache();
			});
			//objA是否拖动排序
			if(settings.objAdrag==true){
				$(settings.objA).parents('tbody.ui-sortable').sortable({
					items:"tr:not('.nodrag')",
					update:function(event,ui){
						that.setCache();
						that.update_table_html();
						that.getCache();
					}
				});
			}
		}
		//objB 促发事件
		if(settings.objB){
			//objB添加一行
			$(settings.objB+','+null).parents('table.change_table').find('tr.thead').on('mouseup','.add_tr',function(){
				that.setCache();
				that.update_table_html();
				that.getCache();
			});
			//objB删除一行
			$(settings.objB).parents('table').on('reduse',function(){
				that.setCache();
				that.update_table_html();
				that.getCache();
			});
			//objB onchange时
			$(document).on('change',settings.objB,function(){
				that.setCache();
				that.update_table_html();
				that.getCache();
			});
			//objB是否拖动排序
			if(settings.objBdrag==true){
				$(settings.objB).parents('tbody.ui-sortable').sortable({
					items:"tr:not('.nodrag')",
					update:function(event,ui){
						that.setCache();
						that.update_table_html();
						that.getCache();
					}
				});
			}
		}
		//$('input.catA').val($('input[name=title]').val());
		//图片浏览->加载
		//$("input[name^='params["+settings.paramsName+"][package][image]']").each(function(e){
		//	$('img[id="'+$(this).attr('name')+'_img"]').attr('src',settings.imgPre+$(this).val());
		//});
	}
	//更新套餐表格
	_package.prototype.update_table_html = function(){
		var obj = $(this.obj);
		var settings = this.settings;
		var tbody_html = '';
		var objA_lenght = $(settings.objA).length;
		var objB_lenght = $(settings.objB).length;
		var that = this;
		//不存在objA时
		//if(objA_lenght==0){
		//	alert('套餐控件A不存在：'+settings.objA);
		//	return false;
		//}
		//不存在objB时
		if(objB_lenght==0){
			//alert('套餐控件B不存在：'+settings.objB);
			return false;
		}
		//得到用于each循环的OBJA对象
		if(settings.objA){
			//获得objA的标签类型
			var objA_tagName = $(settings.objA)[0].tagName;
			//获得objA对象
			if(objA_tagName=='SELECT') //multiple的select时要each option:selected
				OBJA = settings.objA+' option:selected';
			else //非select
				OBJA = settings.objA;
		}else{
			OBJA = [null];//OBJA不存在时，赋值为[null]以便以下each循环一次引导进入OBJB的each循环
		}
		//得到用于each循环的OBJB对象
		if(settings.objB){
			//获得objB的标签类型
			var objB_tagName = $(settings.objB)[0].tagName;
			//获得objB对象
			if(objB_tagName=='SELECT') //multiple的select时要each option:selected
				OBJB = settings.objB+' option:selected';
			else //非select
				OBJB = settings.objB;
		}
		//each->objA、each->objB
		$(OBJA).each(function(d){
			thisA = $(this);
			$(OBJB).each(function(e){
				thisB = $(this);
				var keyA = thisA.attr('lang')?thisA.attr('lang'):thisA.val();//取objA控件的lang值，如lang不存在则取value值
				var keyB = thisB.attr('lang')?thisB.attr('lang'):thisB.val();//取objB控件的lang值，如lang不存在则取value值
				//传递到模板中的变量(中each循环中的,所以次只生成一个tr的html)
				var result = {
					forNum    : e, //OBJB的each循环号e (只有X*X套餐才用得上)
					key       : keyA+keyB, //作为每行的控件序号key
					rowspan   : objB_lenght, //rowspan数(objB数量)
					objAval : thisA.val(), //objA标题(用于入库)
					objAtitle  : thisA.text()?thisA.text():thisA.val(), //objA文本显示(不入库,只作显示)
					objBval : thisB.val(), //objB标题(用于入库)
					objBtitle  : thisB.text()?thisB.text():thisB.val(), //objB文本显示(不入库,只作显示)
					preName   : settings.preName //控件名称前缀
				}
				tbody_html += template.render(settings.name+'_tr_html', result);
			});
		});
		//update html
		obj.find('table.package tbody').html(tbody_html);
		//回调函数
		if(settings.callback!=null)
			settings.callback();
	}
	//记录当前缓存
	_package.prototype.setCache = function(){
		var obj = $(this.obj);
		var settings = this.settings;
		settings.Cache = [];
		//将所有控件的值缓存起来 （.nocache元素除外）
		obj.find('.package [name^="params"]').not('.nocache').each(function(){
			settings.Cache[$(this).attr('name')] = $(this).val();
		});
		//console.log(settings.Cache);
	}
	//恢复缓存
	_package.prototype.getCache = function(){
		var obj = $(this.obj);
		var settings = this.settings;
		//console.log(settings.Cache);
		for(var $item in settings.Cache){
			obj.find("[name='"+$item+"']").val(settings.Cache[$item]);
		}
	}
	//页面加载时,初始化套餐值
	_package.prototype.initCache = function(){
		var obj = $(this.obj);
		var settings = this.settings;
		settings.Cache = [];
		settings.data = $.parseJSON(settings.data);
		if(settings.data)
		$.each(settings.data, function(key,val){
			$.each(val, function(kkk,vvv){
				settings.Cache[settings.preName+'['+key+']['+kkk+']'] = vvv;
			});
		});
	}

})(jQuery);